package com.example.administrator.yanfoxconn.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;

import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.adapter.EmpListAdapter;
import com.example.administrator.yanfoxconn.adapter.IntelligenceGoodsListAdapter;
import com.example.administrator.yanfoxconn.bean.EmpFile;
import com.example.administrator.yanfoxconn.bean.EmpMessage;
import com.example.administrator.yanfoxconn.bean.GoodsMessage;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.constant.FoxContext;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.example.administrator.yanfoxconn.widget.MyListView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import taobe.tec.jcc.JChineseConvertor;

/**
 * 安保部 無紙化辦公 臨時來訪 進廠登記
 * Created by song on 2021/12/06.
 */

public class KOUpdateActivity extends BaseActivity implements View.OnClickListener{
    private final int MESSAGE_SET_TEXT = 1;//掃描成功賦值
    private final int MESSAGE_TOAST = 2;//掃描失敗彈出框
    private final int MESSAGE_NETMISTAKE = 4;//網絡錯誤
    private final int MESSAGE_UP = 3;//提交信息回復
    private final int MESSAGE_SHOW = 5;//顯示提醒
    private final int MESSAGE_CHOISE = 6;//選擇
    private final int MESSAGE_SET_IN_TEXT = 7;//已查验

    private String initStartDateTime; // 初始化开始时间
    private Date selectTime = null;//所選時間
    private Date curDate = null;//當前時間
    private String curDates;//當前時間
    private SimpleDateFormat formatter;
    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    @BindView(R.id.tv_title)
    TextView tvTitle;//標題
    @BindView(R.id.btn_title_right)
    Button btnUp;//提交

    @BindView(R.id.tv_date)
    TextView tvDate;//來訪日期
    @BindView(R.id.sp_area)
    Spinner spArea;//區域
    @BindView(R.id.sp_c_dep)
    Spinner spCDep;//來訪單位
    @BindView(R.id.tr_other)
    TableRow trOther;
    @BindView(R.id.et_c_dep_other)
    EditText etCDepOther;//其他來訪單位
    @BindView(R.id.sp_c_goal)
    Spinner spCGoal;//來訪目的
    @BindView(R.id.tr_goal_other)
    TableRow trCGoalOther;
    @BindView(R.id.et_c_goal_other)
    EditText etCGoalOther;//其他來訪目的
    @BindView(R.id.sp_m_dep)
    Spinner spMDep;//到訪單位
    @BindView(R.id.tr_m_dep_other)
    TableRow trMDepOther;
    @BindView(R.id.et_m_dep_other)
    EditText etMDepOther;//其他到訪單位
    @BindView(R.id.et_c_name)
    EditText etCName;//來訪人
    @BindView(R.id.et_c_num)
    EditText etCNum;//來訪人數
    @BindView(R.id.et_c_car)
    EditText etCCar;//車牌號
    @BindView(R.id.et_m_name)
    EditText etMName;//接待人
    @BindView(R.id.et_in_gate)
    EditText etInlGate;//入廠門崗
    @BindView(R.id.tv_in_gate)
    TextView tvInGate;//入廠門崗
    @BindView(R.id.tr_list_in_gate)
    TableRow trListInGate;
    @BindView(R.id.lv_in_gate)
    MyListView lvInGate;//入廠門崗列表

    private String url;//地址
    private String result;//网络获取结果
    private IntelligenceGoodsListAdapter goodsListAdapter;//物品列表适配器

    private List<String> teamList,teamInList;
    private EmpListAdapter mAdapter,inMAdaptr;
    private List<EmpFile> empFileList;
    private AlertDialog alertDialog1; //信息框
    private String[] areaData = {"請選擇","A區","C區","D區","E區","G區","D區"};
    private String[] cDep = {"請選擇","應急管理局","衛生局","環保局","招商局","其他"};
    private String[] mDep = {"請選擇","污水處理廠","工業安全服務部","財務","其他"};
    private String[] cGoal = {"請選擇","洽公","巡查","其他"};
    private String aeraStr,cDepStr,mDepStr,cGoalStr;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ko_update);
        ButterKnife.bind(this);

        tvTitle.setText("進廠登記");
        btnBack.setOnClickListener(this);
        btnUp.setText("提交");
        btnUp.setVisibility(View.VISIBLE);
        btnUp.setOnClickListener(this);
        etInlGate.setTag("0");//用於判斷是否選擇門崗0;為未選擇,其他為選擇
        formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat formatterUse = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        curDate = new Date(System.currentTimeMillis());
        //获取当前时间
        initStartDateTime = formatterUse.format(curDate);
        tvDate.setText(formatter.format(curDate));
        curDates = formatter.format(curDate);
        getMessage();

        //搜索关键字
        etInlGate.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                trListInGate.setVisibility(View.VISIBLE);
                String a = etInlGate.getText().toString().toUpperCase();
                //调用适配器里面的搜索方法
                inMAdaptr.SearchCity(a);
            }
            @Override
            public void afterTextChanged(Editable editable) {
            }

        });
        //區域
        spArea.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, areaData));
        spArea.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                aeraStr = areaData[position];
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        //來訪單位
        spCDep.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, cDep));
        spCDep.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                cDepStr = cDep[position];
                if (cDepStr.equals("其他")){
                    trOther.setVisibility(View.VISIBLE);
                }else{
                    trOther.setVisibility(View.GONE);
                    etCDepOther.setText("");
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        //來訪目的
        spCGoal.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, cGoal));
        spCGoal.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                cGoalStr = cGoal[position];
                if (cGoalStr.equals("其他")){
                    trCGoalOther.setVisibility(View.VISIBLE);
                }else{
                    trCGoalOther.setVisibility(View.GONE);
                    etCGoalOther.setText("");
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        //到訪單位
        spMDep.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mDep));
        spMDep.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mDepStr = mDep[position];
                if (mDepStr.equals("其他")){
                    trMDepOther.setVisibility(View.VISIBLE);
                }else{
                    trMDepOther.setVisibility(View.GONE);
                    etMDepOther.setText("");
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_title_left:
                finish();
                break;
            case R.id.btn_title_right:

                check();
                break;
        }
    }
    //提交前檢查
    private void check(){
        if(FoxContext.getInstance().getLoginId().equals("")){
            ToastUtils.showLong(KOUpdateActivity.this,"登錄超時,請退出重新登登錄!");
            return;
        }
      if (aeraStr.equals("請選擇")||cDepStr.equals("請選擇")||cGoalStr.equals("請選擇")||mDepStr.equals("請選擇")){
          ToastUtils.showLong(KOUpdateActivity.this,"請選擇正確下拉選項!");
          return;
      }
      if(etCCar.getText().toString().equals("")||etCName.getText().toString().equals("")||etCNum.getText().toString().equals("")||etMName.getText().toString().equals("")){
          ToastUtils.showLong(KOUpdateActivity.this,"請檢查所有輸入內容!");
          return;
      }
      if((cDepStr.equals("其他")&&etCDepOther.getText().equals(""))||(cGoalStr.equals("其他")&&etCGoalOther.getText().equals(""))||(mDepStr.equals("其他")&&etMDepOther.getText().equals(""))){
          ToastUtils.showLong(KOUpdateActivity.this,"請檢查所有'其他'輸入內容!");
          return;
      }
      if (etInlGate.getTag().equals("0")){
          ToastUtils.showLong(KOUpdateActivity.this,"請選擇正確門崗!");
          return;
      }
      if (cDepStr.equals("其他")){
          cDepStr=etCDepOther.getText().toString();
      }
        if (cGoalStr.equals("其他")){
            cGoalStr=etCGoalOther.getText().toString();
        }
        if (mDepStr.equals("其他")){
            mDepStr=etMDepOther.getText().toString();
        }
      upMsessage(tvDate.getText().toString(), aeraStr, etCName.getText().toString(), etCNum.getText().toString(), cDepStr, etCCar.getText().toString(), cGoalStr, mDepStr,etMName.getText().toString(),etInlGate.getText().toString());

    }
    //獲取門崗
    private void getMessage(){
        showDialog();
        final String url = Constants.HTTP_COMMON_FORMS_SERVLET+"?code="+FoxContext.getInstance().getLoginId();

        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url);

                dismissDialog();
                Log.e("---------", "==fff===" + url);
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);

                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();


                        JsonObject jsonObject1 = new JsonParser().parse(String.valueOf(array.get(0))).getAsJsonObject();
                        JsonArray array1 = jsonObject1.get("file").getAsJsonArray();
                        empFileList = new ArrayList<EmpFile>();
                        for (JsonElement type1 : array1) {
                            EmpFile humi1 = gson.fromJson(type1, EmpFile.class);
                            empFileList.add(humi1);
                        }


                        Message message = new Message();
                        message.what = MESSAGE_SET_IN_TEXT;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);

                    } else{
                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                }
            } }.start();
    }


    //提交数据
    private void upMsessage(String c_date,String m_area, String c_name, String c_num,String c_dep,String c_car,String c_goal,String m_dep,String m_name,String m_meng){
        showDialog();
        try {
            String c_date1 =  URLEncoder.encode(URLEncoder.encode(c_date.toString(), "UTF-8"), "UTF-8");
            String m_area1 =  URLEncoder.encode(URLEncoder.encode(m_area.toString(), "UTF-8"), "UTF-8");
            String c_name1 =  URLEncoder.encode(URLEncoder.encode(c_name.toString(), "UTF-8"), "UTF-8");
            String c_dep1 =  URLEncoder.encode(URLEncoder.encode(c_dep.toString(), "UTF-8"), "UTF-8");
            String c_car1 =  URLEncoder.encode(URLEncoder.encode(c_car.toString(), "UTF-8"), "UTF-8");
            String c_goal1 =  URLEncoder.encode(URLEncoder.encode(c_goal.toString(), "UTF-8"), "UTF-8");
            String m_dep1 =  URLEncoder.encode(URLEncoder.encode(m_dep.toString(), "UTF-8"), "UTF-8");
            String m_name1 =  URLEncoder.encode(URLEncoder.encode(m_name.toString(), "UTF-8"), "UTF-8");
            String m_meng1 =  URLEncoder.encode(URLEncoder.encode(m_meng.toString(), "UTF-8"), "UTF-8");
            String m_in_guard_name1=URLEncoder.encode(URLEncoder.encode(FoxContext.getInstance().getName(), "UTF-8"), "UTF-8");
            url = Constants.HTTP_KO_UPDATE + "?c_date="+c_date1 + "&m_area=" + m_area1 + "&c_name=" + c_name1+ "&c_num=" + c_num+ "&c_dep=" + c_dep1+ "&c_car=" + c_car1 + "&c_goal=" + c_goal1 + "&m_dep=" + m_dep1 +"&m_name=" + m_name1 +"&m_meng=" + m_meng1+"&m_in_guard_name="+m_in_guard_name1+"&m_in_guard="+FoxContext.getInstance().getLoginId();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Log.e("-----------", "url-----" + url);
        new Thread() {
            @Override
            public void run() {
                result = HttpUtils.queryStringForPost(url);
                dismissDialog();

                if (result != null) {
                    Log.e("---------", "result==fff===" + result);

                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        Log.e("--fff---------", "result==" + result);

                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);

                    } else{
                        Log.e("-----------", "result==" + result);
                        Message message = new Message();
                        message.what = MESSAGE_UP;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                }else{
                    Message message = new Message();
                    message.what = MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                }
            } }.start();
    }

    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case MESSAGE_TOAST://Toast彈出
                    aboutAlert(msg.obj.toString(),MESSAGE_TOAST);

//                    ToastUtils.showLong(CrossScanActivity.this, msg.obj.toString());
//                    finish();
                    break;
                case MESSAGE_NETMISTAKE://Toast彈出
                    ToastUtils.showLong(KOUpdateActivity.this,R.string.net_mistake);
                    break;
                case MESSAGE_SET_IN_TEXT:
                    setInText();
                    break;
                case MESSAGE_UP://提交響應
                    worningAlert(msg.obj.toString(),MESSAGE_TOAST);
//                    ToastUtils.showLong(CrossScanActivity.this, msg.obj.toString());

            }
            super.handleMessage(msg);
        }
    };
    private void setInText() {

        teamList = new ArrayList<>();
        for (int i = 0;i<empFileList.size();i++){
            teamList.add(change1(empFileList.get(i).getID()+","+empFileList.get(i).getAQ1()+"-"+empFileList.get(i).getAQ2()+"-"+empFileList.get(i).getAQ3()+"-"+empFileList.get(i).getAQ4()));
        }
        inMAdaptr = new EmpListAdapter(KOUpdateActivity.this,teamList);
        lvInGate.setAdapter(inMAdaptr);

        //稽核門崗列表,選中后1:tit賦值,2:列表隱藏
        inMAdaptr.OnClickSetText(new EmpListAdapter.OnClickSetText() {
            @Override
            public void OnClickxt(String tit) {
                etInlGate.setText(tit.split(",")[1]);
                etInlGate.setTag(tit.split(",")[0]);
//                paramMap.put("mengang", empFileList.get(position).getID());
                inMAdaptr.SearchCity("");
                trListInGate.setVisibility(View.GONE);
            }

            @Override
            public void OnClicktv(String tit, String tv) {

            }
        });
    }

    //简体转成繁体
    public String change(String changeText) {
        try {
            JChineseConvertor jChineseConvertor = JChineseConvertor.getInstance();
            changeText = jChineseConvertor.s2t(changeText);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return changeText;
    }
    //繁体转成简体
    public String change1(String changeText) {
        try {
            JChineseConvertor jChineseConvertor = JChineseConvertor
                    .getInstance();
            changeText = jChineseConvertor.t2s(changeText);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return changeText;
    }


    private void aboutAlert(String msg, final int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示信息")
                .setMessage(msg)
                .setCancelable(false)
                .setPositiveButton("確認", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
                        if (type==MESSAGE_TOAST){
                            finish();
                        }
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }
    private void worningAlert(String msg, final int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示信息")
                .setMessage(msg)
                .setCancelable(false)
                .setPositiveButton("確認", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
                        if (type==MESSAGE_TOAST){
                            finish();
                        }
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }
}


